package kuber

import (
	"common_demo/internal/config"
	"common_demo/pkg/kuber"
	"common_demo/pkg/logger"
	"context"

	"github.com/gin-gonic/gin"
	coreV1 "k8s.io/api/core/v1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
)

type KuberHandler struct {
	kuberCli *kubernetes.Clientset
}

func NewKuberHandler(ctx context.Context) *KuberHandler {
	kuberCli, err := kuber.NewKuberClient(config.Config.Kuber)
	if err != nil {
		logger.Errorf("failed to connect to kubernetes, error: %s", err.Error())
	}
	return &KuberHandler{
		kuberCli: kuberCli,
	}
}

func (handler *KuberHandler) GetNamespaces(ctx *gin.Context) ([]coreV1.Namespace, error) {
	client, err := kuber.NewKuberClient(config.Config.Kuber)
	if err != nil {
		return nil, err
	}

	namespaceList, err := client.CoreV1().Namespaces().List(ctx, v1.ListOptions{})
	if err != nil {
		return nil, err
	}
	return namespaceList.Items, nil
}
